<?php
/**
 * Created by PhpStorm.
 * User: yuliang
 * Date: 2017/6/8
 * Time: 下午10:47
 */

namespace app\admin\controller;

use app\common\controller\Api;
use think\Db;

class User extends Api
{
    // 用户列表，手机号搜索
    public function userList(){
        $result = $this->checkAuthToken(input('token'),input('uid'));
        if(!$result){
            return api_error('9999','请重新登陆！');
        }
        $page = input('page')?input('page'):1;
        $pageSize = 10;
        $mobile = input('mobile');
        if($mobile){
            $where['mobile'] = ['like','%'.$mobile.'%'];
        }else{
            $where = true;
        }
        $user = model('User')->field('uid,real_name,nick_name,create_time,last_login_time,status')->where($where)->page($page,$pageSize)->select();
        $num = model('User')->where($where)->count();
        $data['page'] = ceil($num/$pageSize);
        $data['data'] = $user;
        return api_return('操作成功！',$data);
    }

    // 更改用户状态，禁用／解禁
    public function changeUser(){
        $result = $this->checkAuthToken(input('token'),input('uid'));
        if(!$result){
            return api_error('9999','请重新登陆！');
        }
        $uid = input('id');
        $status = input('status');
        $update_time = date('Y-m-d H:i:s',time());
        $result = model('User')->save(['status'=>$status,'update_time'=>$update_time],['uid'=>$uid]);
        if($result !== false){
            return api_return('操作成功',array());
        }else{
            return api_error('60001','操作失败！');
        }
    }

    // 添加管理员
    public function addAdmin(){
        $result = $this->checkAuthToken(input('token'),input('uid'));
        if(!$result){
            return api_error('9999','请重新登陆！');
        }
        $uid = input('uid');
        if($uid != 1){
            return api_error('60002','对不起，您无权操作！');
        }
        $data = input('post.');
        $rule = [
            'name' => 'require',
            'account' => 'require|alphaDash',
            'password' => 'require|min:6',
            'repassword'=> 'require|confirm:password'
        ];
        $validate = $this->validate($data,$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        $data['password'] = md5(md5($data['password']).config('salt_key'));
        $data['create_time'] = date('Y-m-d H:i:s',time());

        unset($data['uid'],$data['repassword'],$data['token']);
        $result = Db::name('admin')->insert($data);
        if($result){
            return api_return('操作成功！',array());
        }else{
            return api_error('60003','添加管理员失败！');
        }
    }

    // 禁用／启用管理员
    public function operateAdmin(){
        $result = $this->checkAuthToken(input('token'),input('uid'));
        if(!$result){
            return api_error('9999','请重新登陆！');
        }
        $uid = input('uid');
        if($uid != 1){
            return api_error('60004','对不起，您无权操作！');
        }
        $data['status'] = input('post.status');
        $data['id'] = input('post.id');
        $rule = [
            'id' => 'require|number',
            'status' => 'require|in:0,1'
        ];
        $validate = $this->validate($data,$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        $result = Db::name('admin')->where('id',$data['id'])->update($data);
        if($result !== false){
            return api_return('操作成功！',array());
        }else{
            return api_error('60005','修改失败！');
        }
    }

    // 管理员列表
    public function adminList(){
        $result = $this->checkAuthToken(input('token'),input('uid'));
        if(!$result){
            return api_error('9999','请重新登陆！');
        }
        $page = input('page',1);
        $list = Db::name('admin')->field('id,name,login_count,login_ip,login_time,status')->page($page,10)->order('id asc')->select();
        $count = Db::name('admin')->count();
        $data['page'] = ceil($count/10);
        $data['data'] = $list;
        return api_return('操作成功！',$list);
    }

    // 意见反馈列表
    public function feedBackList(){
        $page = input('page')?input('page'):1;
        $pageSize = 10;
        $data = Db::name('feedback')->page($page,$pageSize)->order('id desc')->select();
        $total = Db::name('feedback')->count();
        $result['page'] = ceil($total/$pageSize);
        $result['data'] = $data;
        return api_return('操作成功！',$result);
    }

    // 用户绑定列表
    public function listSell(){
        $page = input('page')?input('page'):1;
        $pageSize = 10;
        $orderModel = model('CourseOrder');
        if(trim(input('post.search'))){
            $where['a.bind_code'] = input('search');

            // 查询绑定后用户消费总额
            $users = Db::name('sell')->field('uid,bind_time')->where(['bind_code'=>input('search')])->select();
            if(!empty($users)){
                $y = [];
                foreach ($users as $v){
                    $x = $orderModel->field('sum(price) as count')->where(['user_id'=>$v['uid'],'status'=>1])->where('create_time','> time',$v['bind_time'])->group('user_id')->find();
                    $y[] = $x['count'];
                }
                $total = array_sum($y);
            }else{
                $total = 0;
            }

        }else{
            $where = "bind_code != ''";
            $total = 0;
        }


//        $subsql = Db::table('jy_course_order')->where(['status'=>1])->field('user_id,sum(pay_price) prices,create_time')->group('user_id')->buildSql();
//        Db::table('jy_sell')->alias('a')->field('a.uid,a.bind_code,a.bind_time,b.real_name,b.nick_name,c.prices,c.create_time')->join('jy_oauth_user b','a.uid = b.uid')
//            ->join([$subsql=>'c'],'a.uid = c.user_id')->where($where)->page($page,$pageSize)->select();
        $list = Db::table('jy_sell')->alias('a')->join('jy_oauth_user b','a.uid = b.uid','LEFT')->field('a.uid,a.bind_code,a.bind_time,b.real_name,b.nick_name,a.bind_uid')->where($where)->page($page,$pageSize)->select();
        $sum = Db::table('jy_sell')->alias('a')->join('jy_oauth_user b','a.uid = b.uid','LEFT')->where($where)->count();
        $userModel = model('User');
        if(!empty($list)){
            foreach ($list as &$value){
                $user = $userModel->field('real_name,nick_name')->where(['uid'=>$value['bind_uid']])->find();
                $value['bind_name'] = $user['real_name']?$user['real_name']:$user['nick_name'];
                $count = $orderModel->field('sum(price) as count')->where(['user_id'=>$value['uid'],'status'=>1])->where('create_time','> time',$value['bind_time'])->group('user_id')->find();
                $value['price'] = $count['count']?$count['count']:0;
            }
        }else{
            $list = array();
        }
        $result['data'] = $list;
        $result['page'] = ceil($sum/$pageSize);
        $result['count'] = $sum;
        $result['total'] = $total;
        return api_return('操作成功！',$result);
    }

}